package com.huanzhu.asuper.supervisionapp.cjbjdudao;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.databinding.DataBindingUtil;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.huanzhu.asuper.supervisionapp.cjbjdudao.R;
import com.huanzhu.asuper.supervisionapp.cjbjdudao.WebApplication;
import com.huanzhu.asuper.supervisionapp.cjbjdudao.base.BaseActivity;
import com.huanzhu.asuper.supervisionapp.cjbjdudao.base.CoreService;
import com.huanzhu.asuper.supervisionapp.cjbjdudao.base.ServerManager;
import com.huanzhu.asuper.supervisionapp.cjbjdudao.databinding.ActivityHzWebViewBinding;
import com.huanzhu.asuper.supervisionapp.cjbjdudao.uitls.AppUtils;
import com.huanzhu.asuper.supervisionapp.cjbjdudao.uitls.EmptyViewUtils.OnNetWorkRetryListener;
import com.huanzhu.asuper.supervisionapp.cjbjdudao.uitls.EmptyViewUtils.ShowExceptionUIHelper;
import com.huanzhu.asuper.supervisionapp.cjbjdudao.uitls.NetUtils;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.net.InetAddress;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;


public class HZWebAcivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {


    private ActivityHzWebViewBinding binding;
    private WebSettings settings;
    private String failiUrl;
    private long exitTime;
    String ip;
    String port="8899";
    public static ServerManager mServerManager;
    Server andServer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_hz_web_view);
        whiteStatusBar();
        initSetings();
        initShowExceptionView(binding.rvItem, new OnNetWorkRetryListener() {
            @Override
            public void retry() {
            }
        });
//        mServerManager=new ServerManager(this);
//        mServerManager.register();
          andServer=   AndServer.webServer(this)
                .port(8899)
                .timeout(10, TimeUnit.SECONDS)
                .listener(new Server.ServerListener() {
                    @Override
                    public void onStarted() {
                        Log.d("=====","启动成功");
                        ip=NetUtils.getLocalIPAddress().getHostAddress();
                        setLoadUrl();
//                        ServerManager.onServerStart(CoreService.this, address.getHostAddress());
                    }

                    @Override
                    public void onStopped() {
                        Log.d("=====","停止服务");
                    }

                    @Override
                    public void onException(Exception e) {
                        Log.d("=====","服务异常");
                        e.printStackTrace();
//                        ServerManager.onServerError(CoreService.this, e.getMessage());
                    }
                })
                .build();
        andServer.startup();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mServerManager.unRegister();
        andServer.shutdown();
    }
    public  void  setIP(String ipp){
        ip=ipp;
    }

    public  void  setLoadUrl(){
        binding.wvWebview.loadUrl( "http://"+ip+":8899");
    }

    @Override
    public void onRefresh() {
        binding.swRefresh.setRefreshing(false);
        if (andServer.isRunning()){
            setLoadUrl();
        }else {
            andServer.shutdown();
            andServer.startup();
        }


    }

    private void initSetings() {
        binding.swRefresh.setColorSchemeResources(R.color.item_task_details_3fcb98);
        binding.swRefresh.setOnRefreshListener(this);
//        binding.wvWebview.loadUrl("file:///android_asset/dist/index.html");
//        binding.wvWebview.loadUrl( "http://192.168.0.45:8080/h5-cli/TaskList");
//                binding.wvWebview.loadUrl( " http://192.168.0.98:3000/#/mb");


//        binding.wvWebview.addJavascriptObject(new WebViewJsApi(this), null);
        settings = binding.wvWebview.getSettings();
        // 设置可以使用localStorage
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setAllowUniversalAccessFromFileURLs(true);
        binding.wvWebview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                binding.progressBar.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }
        });
        binding.wvWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                return super.shouldOverrideUrlLoading(webView, s);
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
                return super.shouldOverrideUrlLoading(webView, webResourceRequest);
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                binding.progressBar.setVisibility(View.VISIBLE);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                binding.progressBar.setVisibility(View.GONE);
            }
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                Logger.d("----ibms------", "证书错误: " + error);
                handler.proceed();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    binding.wvWebview.getSettings().setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
                }
            }



            // 旧版本，会在新版本中也可能被调用，所以加上一个判断，防止重复显示
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return;
                }
                failiUrl = failingUrl;
                mShowExceptionUIHelper.setNotice_noContent("加载失败！请稍后再试");
//                mShowExceptionUIHelper.refreshUI(ShowExceptionUIHelper.NETWORK_ERROR);

            }

            @Override
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(webView, webResourceRequest, webResourceError);
                if (webResourceRequest.isForMainFrame()) {
                    failiUrl = webResourceRequest.getUrl().toString();
                    int statusCode = webResourceError.getErrorCode();
                    mShowExceptionUIHelper.setNotice_noContent("加载失败！请稍后再试");
//                    mShowExceptionUIHelper.refreshUI(ShowExceptionUIHelper.NETWORK_ERROR);


                }
            }
        });
        binding.wvWebview.setWebContentsDebuggingEnabled(true);
        settings.setUserAgentString(settings.getUserAgentString() + "dxh_android_app");
        String appCaceDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        settings.setAppCachePath(appCaceDir);//设置Application缓存API是否开启，默认false


    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Long secondTime = System.currentTimeMillis();
        if (secondTime - exitTime > 800) {
            Toast.makeText(WebApplication.getInstance(), "再次点击退出", Toast.LENGTH_SHORT).show();
            //更新firstTime
            exitTime = secondTime;
            return;
        } else {//否则退出程序
            finish();
            System.exit(0);
        }
    }

    @Override
    public void finish() {
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        super.finish();
    }

    private void back() {
        if (binding.wvWebview.canGoBack()) {
            binding.wvWebview.goBack();
        } else {
            finish();
        }
    }


}
